package com.easy.clickhouse;

import ru.yandex.clickhouse.settings.ClickHouseProperties;

import java.util.Iterator;
import java.util.List;

/**
 * 集群定义
 * @author jetlag
 *
 */
public class ClickHouseCluster {
    
    /** 集群名称*/
    private String name;
    /** 用户名*/
    private String username;
    /** 密码*/
    private String password;
    /** 服务器定义*/
    private List<ClickHouseServer> servers;
    
    /** clickhouse地址*/
    private transient volatile String clusterAddress;
    /** clickhouse配置*/
    private transient volatile ClickHouseProperties properties;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<ClickHouseServer> getServers() {
        return servers;
    }

    public void setServers(List<ClickHouseServer> servers) {
        this.servers = servers;
    }

    public void setClusterAddress(String clusterAddress) {
        this.clusterAddress = clusterAddress;
    }

    public ClickHouseProperties getProperties() {
        return properties;
    }

    public void setProperties(ClickHouseProperties properties) {
        this.properties = properties;
    }

    /**
     * 获取集群地址
     * @return
     */
    public String getClusterAddress() {
        if (clusterAddress == null) {
            synchronized (this) {
                if (clusterAddress == null) {
                    StringBuilder builder = new StringBuilder();
                    builder.append(ClickHouseServer.URL_PREFIX);
                    Iterator<ClickHouseServer> iterator = servers.iterator();
                    while(iterator.hasNext()) {
                        ClickHouseServer ckServer = iterator.next();
                        builder.append(ckServer.getHost()).append(":")
                               .append(ckServer.getHttp()).append(",");
                    }
                    builder.deleteCharAt(builder.lastIndexOf(","));
                    clusterAddress = builder.toString();
                }
            }
        }
        return clusterAddress;
    }
    
    /**
     * 获取集群配置
     * @return
     */
    public ClickHouseProperties getClusterProperties() {
        if (properties == null) {
            synchronized (this) {
                if (properties == null) {
                    properties = new ClickHouseProperties();
                    properties.setUser(username);
                    properties.setPassword(password);
                    properties.setCompress(true);
                    properties.setDecompress(true);
                }
            }
        }
        return properties;
    }
}
